/* filter */
import Filter from '@src/filter/filter.js';
/* util */
import _ from 'lodash';
import { formatDate } from 'pub-bbx-utils';
import { isEmptyStringObject } from '@src/util/function';

/**
 * 初始化搜索表单的值
 *
 * @param field 自定义字段
 * @return tv 格式化后的初始化字段
 */
export function initVal(field) {
  if (field.defineType !== null && field.defineType !== undefined) {
    return field.defineType;
  }

  let tv = '';

  // 地址的默认值初始化为对象
  if (field.formType == 'address') tv = {};
  if (field.formType == 'date' || field.formType == 'datetime') tv = [];
  if (field.formType === 'link') {
    tv = {};
  }
  if (field.fieldName === 'tags') {
    tv = [];
  }
  if (field.formType === 'area' || field.formType === 'cascader') {
    tv = [];
  }

  if (field.formType === 'user') {
    tv = [];
  }
  if (field.fieldName === 'status') {
    tv = [];
  }

  if (field.formType === 'select' && field.setting.isMulti) {
    tv = [];
  }

  return tv;
}

/* 动态查询条件 */
export function matchOperator(field) {
  let formType = field.formType;
  let operator = '';

  switch (formType) {
  case 'date':
  case 'datetime': {
    operator = 'between';
    break;
  }
  case 'select': {
    if (field.setting && field.setting.isMulti) {
      operator = 'contain';
    } else {
      operator = 'eq';
    }
    break;
  }
  case 'cascader': {
    operator = 'cascader';
    break;
  }
  case 'user': {
    operator = 'object_in';
    break;
  }
  case 'address': {
    operator = 'array_like';
    break;
  }
  case 'location': {
    operator = 'array_like';
    break;
  }
  case 'related_task': {
    operator = 'array_eq';
    break;
  }
  case 'formula': {
    operator = 'eq';
    break;
  }
  case 'customer': {
    operator = 'array_eq';
    break;
  }
  case 'linkman': {
    operator = 'array_eq';
    break;
  }
  // 废弃 使用like模糊搜索
  // case 'product': {
  //   operator = 'array_eq';
  //   break;
  // }
  case 'customerAddress': {
    operator = 'array_like';
    break;
  }
  default: {
    operator = 'like';
    break;
  }
  }

  return operator;
}

/* 将form对象转成高级搜索参数对象 */
export function packToAdvancedSearchParams(fields, form) {
  const isSystemFields = fields.filter(f => f.isSystem);
  const notSystemFields = fields.filter(f => !f.isSystem);

  let params = {
    conditions: []
  };

  let tv = null;
  let fn = '';

  // 系统固定字段
  for (let i = 0; i < isSystemFields.length; i++) {
    tv = isSystemFields[i];
    fn = tv.fieldName;

    if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
      if (fn !== 'status') {
        continue;
      }
    }

    if(['date', 'datetime'].includes(tv.formType)){
      params[`${fn}Start`] = form[fn][0];
      params[`${fn}End`] = form[fn][1];
      continue;
    }

    if (fn === 'status') {
      let parentStatus = [];
      let childStatus = [];

      form.status && form.status.forEach(item => {
        item[0] && parentStatus.push(item[0]);
        item[1] && childStatus.push(item[1]);
      });

      params.customStatusList = childStatus;
      params.statusList = [...new Set(parentStatus)];
      continue;
    }

    if (tv.formType === 'date' || tv.formType === 'datetime') {
      params[fn] = form[fn].map(t => formatDate(t, 'YYYY/MM/DD')).join('-');
      continue;
    }

    // 系统字段客户、客户联系人、客户地址、产品特殊处理
    if (
      tv.formType === 'customer' ||
      tv.formType === 'customerAddress' ||
      tv.formType === 'linkman'
    ) {
      let key = tv.formType != 'customerAddress' ? 'id' : 'label';

      params.conditions.push({
        property: fn,
        operator: tv.operator,
        value: form[fn],
        key: key
      });
      continue;
    }
    // 产品是属于子表单 （后续可支持相关子表单查询）需要传入查对应的子表单的fieldName
    if(tv.formType === 'product' ) {
      params.conditions.push({
        property: fn,
        operator: tv.operator,
        value: form[fn],
        isSubForm: 1,
        subFormFieldName: `${tv.fieldName}_name` // 需要查询的子表单的字段
      });
      continue;
    }

    // 编号特殊处理
    if (tv.formType === 'serialNumber') {
      params.conditions.push({
        property: fn,
        operator: tv.operator,
        value: form[fn]
      });
      continue;
    }

    // 关联工单
    if (tv.originalFormType === 'related_task') {
      params.conditions.push({
        key: 'taskNo',
        property: fn,
        operator: tv.operator,
        value: form[fn]
      });
      continue;
    }

    params[fn] = form[fn];
  }

  // 自定义字段
  for (let i = 0; i < notSystemFields.length; i++) {
    let key = null;
    tv = notSystemFields[i];
    fn = tv.fieldName;

    if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
      continue;
    }

    // 空对象
    if (
      typeof form[fn] === 'object' &&
      !Array.isArray(form[fn]) &&
      !Object.keys(form[fn]).length
    ) {
      continue;
    }

    // 日期
    if (tv.originalFormType === 'date') {
      params.conditions.push({
        property: fn,
        operator: tv.operator,
        betweenValue1: formatDate(form[fn][0], 'YYYY-MM-DD'),
        betweenValue2: formatDate(form[fn][1], 'YYYY-MM-DD')
      });
      continue;
    }

    // 日期时间
    if (tv.originalFormType === 'datetime') {
      params.conditions.push({
        property: fn,
        operator: tv.operator,
        betweenValue1: formatDate(form[fn][0], 'YYYY-MM-DD HH:mm:ss'),
        betweenValue2: `${formatDate(form[fn][1], 'YYYY-MM-DD')} 23:59:59`
      });
      continue;
    }

    // 多级选择
    if (tv.formType === 'cascader') {
      params.conditions.push({
        property: fn,
        operator: tv.operator,
        inValue: form[fn]
      });
      continue;
    }

    // 地址
    if (tv.formType === 'address') {
      key = 'all';

      let address = {
        property: fn,
        operator: tv.operator
      };

      let isEmpty = isEmptyStringObject(form[fn]);

      if (!isEmpty) {
        address.value = Filter.prettyAddress(form[fn]);
        params.conditions.push(address);
      }
      continue;
    }

    // 关联工单
    if (tv.originalFormType === 'related_task') {
      key = 'taskNo';
    }

    // 地址
    if (tv.originalFormType === 'location') {
      key = 'all';
    }

    // 位置
    if (tv.originalFormType === 'related_task') {
      key = 'address';
    }

    // 人员
    if (tv.originalFormType === 'user') {
      key = 'userId';
      params.conditions.push({
        key,
        property: fn,
        operator: tv.operator,
        inValue: form[fn]
      });
      continue;
    }

    params.conditions.push({
      property: fn,
      operator: tv.operator,
      value: form[fn],
      key
    });
  }

  return params;
}

/* 过滤并格式化高级搜索字段 */
export function convertAdvanceSearchFields(fields, origin) {
  let f = {};

  return fields
    .filter(f => f.isSearch || f.isSystem)
    .map(field => {
      f = _.cloneDeep(field);

      let formType = f.formType;

      if (formType === 'datetime') {
        formType = 'date';
      }

      if (f.fieldName === 'customer') {
        formType = 'customer';
      }

      if (origin[field.fieldName]) {
        f.isNotModify = true;
      }

      return Object.freeze({
        ...f,
        isNull: 1,
        formType,
        originalFormType: f.formType,
        orderId: f.isSystem ? f.orderId - 100 : f.orderId,
        operator: matchOperator(f)
      });
    })
    .sort((a, b) => a.orderId - b.orderId);
}
